<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
    <meta charset="UTF-8">
    <title>结算</title>
    <link rel="stylesheet" href="./css/style.min.css">
    <style>
        #cart-pg .main {
            margin-bottom: 150px;
            padding-bottom: 10px;
        }
    </style>
</head>
<script type="text/javascript">
    window.onload=function () {
            document.addEventListener('touchstart',function (event) {
                if(event.touches.length>1){
                    event.preventDefault();
                }
            })
            var lastTouchEnd=0;
            document.addEventListener('touchend',function (event) {
                var now=(new Date()).getTime();
                if(now-lastTouchEnd<=300){
                    event.preventDefault();
                }
                lastTouchEnd=now;
            },false)
        }
</script>

<body>
    <div id="cart-pg" class="cart-pg cl">
        <header class="cl" v-show="header.show">
            <div class="nav-bar cl">
                <span class="goback arrow_l" @click="goback"></span>
                <span class="page-name">支付</span>
            </div>
        </header>
        <div class="main cl">
            <div class="receiver-info" v-cloak>
                <a :href="addr_link">
                    <p class="contacts">
                        <span class="name">{{addrdetail.recevier||"请选择收货地址"}}</span>
                        <span class="phone">{{receviercell}}</span>
                        <label class="addr-def" v-show="addrdetail.def_addr">默认</label>
                    </p>
                    <p class="addr-details"><span class="map-ico"></span>{{addrdetail.addr_str + addrdetail.addr||"请添加详细地址"}}</p>
                    <span class="change-addr"></span></a>
            </div>
            <goodslist :list="orderdata" :shop="shoplist" :stock="stock_json" class="order-confirm-goods"></goodslist>
            <div class="my-coupon-wrap cl order-confirm-coupon" v-cloak>
                <div class="my-coupon cl">
                    <a :href="'c-clip-coupons.html?storeid=' + store_ids + '&cartIds=' + cartids + '&addressId=' + addrid + '&couponIds=' + coupon_id + '&couponcode=' + _couponCodes " class="cl">
                        <p>我的优惠券</p>
                        <span>共<em class="coupon-counts" v-cloak>{{couponTotail}}</em>张优惠券<i class="arrow-right"></i></span></a>
                </div>
            </div>
            <div class="total-wrap cl">
                <hr/>
            <div class="total-body order-confirm-total" v-cloak>
                <h4 v-if="coupon_amount > 0">优惠金额:￥{{coupon_amount.toFixed(2)}}</h4>
                <h4>订单小计：￥{{parseFloat(order.totalAmount || 0).toFixed(2)}}</h4>
                <h5>运费：{{freight>0?freight:"请与卖家确认发货物流公司及费用信息"}}</h5>
                <p style="font-size: 12px;color: #eb0000;">如需改价，请提交订单后联系卖家。</p>
            </div>
        </div>
        </div>

        <div class="chkout-btm-bar">
            <div class="check"><a href="#" @click.prevent="order_submit">提交订单</a></div>
            <div class="total-accout">
                <h4>合计：<span v-cloak>￥{{totalaccout.toFixed(2)}}</span></h4>   
            </div>
        </div>
        <toast ref="toast"></toast>
        <confirm ref="confirm"></confirm>
        <div class="loading" v-show="loading"></div>
    </div>
    <script type="text/template" id="goodslist">
        <table v-cloak v-show="shop[0]['shop_name']">
                <colgroup>
                    <col width="100px">
                    <col>
                </colgroup>
                <thead>
                    <tr>
                        <th colspan="2">
                            <!-- <span class="store-character">自营/会员店</span> -->
                            <span class="chkout">{{shop[0]['shop_name']}}</span></th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="goods in list">
                        <td>
                            <div class="img-wrap"><img :src="goods['sku']?goods['sku']['small_img']:''"></div>
                        </td>
                        <td>
                            <a href="#" class="order-title" >{{goods['sku']?goods['sku']['goods_name']:''}}</a>
                            <p class="price-wrap cl"><span class="price"><em>￥</em>{{goods.price.toFixed(2)}}</span><span class="counts">x{{goods.qty}}</span><span class="stock-flag" :class="{lack:stock_flag}">{{cpu_stock_str(goods.skuId)}}</span></p>
                        </td>
                    </tr>
                </tbody>
            </table>
    </script>
    <script src="./js/lib/vue.js"></script>
    <script src="http://static.jdhui.com/lib/vue-resource/1.2/vue-resource.js"></script>
    <script src="./js/min/config.min.js"></script>
    <script type="text/javascript" src="./js/min/common.min.js"></script>
    <script src="./js/min/component.min.js"></script>
    <script>
        var toast = new component.popup.toast();
        var confirm = new component.popup.confirm({
            name:"confirm",
            type:"confirm"
        });
        var store_id = parseInt(APP.getQueryString("storeid"));
        var cartid = APP.getQueryString("cartIds");
        var bn_cartid = APP.getQueryString("bncartid");
        var _addressId = APP.getQueryString("addressId");
        var addressId = "";
        var n_cartid = "";
        var _couponIds=APP.getQueryString('couponIds');
        var _couponCodes=APP.getQueryString('couponcode');
        var _coupon_amount=APP.getQueryString('amount');     
        console.log(_couponIds);
        if (_couponIds=="null"||_couponIds==null) {
            _couponIds=""
        }
        if (_couponCodes=="null"||_couponCodes==null) {
            _couponCodes=""
        }
        if (_coupon_amount=="null"||_coupon_amount==null) {
            _coupon_amount=""
        }
        var backUrl = encodeURIComponent(window.location.href);
        if (_addressId) {
            addressId = parseInt(APP.getQueryString("addressId"));
        } else {
            addressId = "";
        }
        if (bn_cartid) {
            n_cartid = bn_cartid;
            ncartname = "bncartid"
        } else {
            n_cartid = cartid;
            ncartname = "cartIds";
        }
        Vue.component("goodslist", {
            template: "#goodslist",
            props: ['list', 'shop','stock'],
            data: function() {
                return {
                    stock_flag:false
                }
            },
            mounted: function() {
                
            },
            methods:{
                cpu_stock_str: function(m){
                    if (this.stock.code==1) {
                        return "有货"
                    }else if(this.stock.code=="41000"||this.stock.code=="41001"){
                        if (this.stock.obj[m]) {
                            this.stock_flag=true;
                            return "当前地区无货"
                        }else{
                            return "有货"
                        }
                    }
                }
            }
        })
        var app = new Vue({
            el: "#cart-pg",
            data: {
                header: {
                    show: !APP.iswechat()
                },
                totalaccout: 0,
                order: {},
                orderdata: [],
                addrdetail: "",
                shoplist: [{
                    shop_name: ""
                }],
                addrid: addressId,
                cartids: cartid,
                coupon_id : _couponIds,
                coupon_amount:parseFloat(_coupon_amount),
                store_ids:store_id,
                submit_ok: true,
                loading:true,
                couponTotail:'',
                freight:"",
                pop_hide: true,
                stock_qry:{
                    shopId:store_id,
                    cartIds:cartid,
                    addressId:addressId,
                    couponIds:_couponIds
                },
                stock_json:""
            },
            mounted: function() {
                var that = this;
                Vue.http.options.xhr = {
                    withCredentials: true
                }
                Vue.http.options.credentials = true;
                Vue.http.post(APIJAVA + 'c/mobile/order/settle/json', {
                    shopId: store_id,
                    cartIds: n_cartid
                }, {
                    emulateJSON: true
                }).then(function(_res) {
                    var _cartid = [];
                    var tmp_arr = [];
                    var couponId = location.search;
                    if (_res.body.code == 1 && _res.body.obj) {
                        if(_res.body.obj.couponList == null){
                            that.couponTotail = 0;
                        }else{
                            that.couponTotail = _res.body['obj']['couponList'].length;
                        }
                        //that.couponTotail = _res.body['obj']['couponList'].length;
                        that.order = _res.body.obj.order;
                        for (var i = 0; i < _res.body['obj']['carts'].length; i++) {
                            var _status=_res.body['obj']['carts'][i]&&_res.body['obj']['carts'][i]['sku']&&_res.body['obj']['carts'][i]['sku']['validateStatus']&&_res.body['obj']['carts'][i]['sku']['validateStatus'] == 1
                            if (_status) {
                                that.orderdata.push(_res.body['obj']['carts'][i]);
                                that.totalaccout += parseFloat(_res.body['obj']['carts'][i]['sku']['price']) * parseInt(_res.body['obj']['carts'][i]['qty']);
                                _cartid.push(_res.body['obj']['carts'][i]['id']);
                            }
                        }
                        if((couponId.indexOf('couponIds') >= 0 && that.coupon_id != "")||(couponId.indexOf('couponcode') >= 0&&_couponCodes!="")){
                                that.totalaccout -= that.coupon_amount;
                            //for (var i = 0; i < _res.body['obj']['couponList'].length; i++) {
                                 
                                // if (_res.body['obj']['couponList'][i]['status'] == 1) {
                                //     that.totalaccout -= _res.body['obj']['couponList'][i]['amount'];
                                //     console.log(that.totalaccout);
                                // }
                            //}
                        }
                        if (bn_cartid) {
                            that.cartids = bn_cartid;
                        } else {
                            that.cartids = _cartid.join(',')
                        }
                        that.shoplist = eval(_res.body.obj.shopList)
                        that.addrlist = eval(_res.body.obj.addrList)
                        that.loading=false;
                            // that.totalaccout =_res.body.obj.order.totalGoodsAmount;
                    }  else if(_res.body.code==0 && _res.body.obj==null){
                        that.$refs.toast.show(_res.body.message + '，即将跳转...', 5000);
                        setTimeout(function() {
                            window.location.href = "goods-list.html?storeid=" + store_id
                        }, 5000)
                    }

                }, function() {
                    that.$refs.toast.show('网络连接失败，请稍候重试', 3000);
                })
                Vue.http.get(APIPHP + 'index.php?r=member/u/recipient&storeid=' + store_id, {
                    emulateJSON: true
                }).then(function(_res) {
                    if (_res.body.error_code == 200) {
                        var addrlist = _res.body.data.data;
                        if (addressId == "") {
                            for (var i = 0; i < addrlist.length; i++) {
                                if (addrlist[i]['def_addr'] == 1) {
                                    that.addrdetail = addrlist[i];
                                    that.addrid = addrlist[i]['addr_id']
                                }
                            }
                        } else {
                            for (var i = 0; i < addrlist.length; i++) {
                                if (addrlist[i]['addr_id'] == addressId) {
                                    that.addrdetail = addrlist[i];
                                    that.addrid = addressId;
                                }
                            }
                        }

                    }else if (_res.body.error_code == 400) {
                        that.$refs.toast.show(_res.body.msg + '，即将跳转...', 3000);
                        setTimeout(function() {
                            window.location.href = "login.html?storeid=" + store_id + "&redirectUrl=" + backUrl
                        }, 3000)
                    }
                    setTimeout(function(){
                        that.chkfreight();
                        that.chkstock();  
                    },0)
                
                }, function() {
                    console.log("请求错误")
                })
                
            },
            methods: {
                hidefn:function(){
                    this.pop_hide = !this.pop_hide;
                },
                goback: function() {
                    window.history.go(-1);
                },
                order_submit: function(e) {
                    if (this.addrid == '') {
                        this.$refs.toast.show('请选择收货地址！');
                        return;
                    }
                    if (this.submit_ok) {
                        this.loading = true;
                        e.target.text = "正在提交...";
                        var that = this;
                        Vue.http.post(APIJAVA + 'c/mobile/order/submit?shopId='+ store_id+"&cartIds="+n_cartid+"&addressId="+that.addrid+"&couponIds="+_couponIds+"&couponCodes="+_couponCodes, { }, {
                            emulateJSON: false
                        }).then(function(_res) {
                            that.loading = false;
                            e.target.text = "提交订单"
                            if (_res.body.code == 1) {
                                window.location.href = "order-details.html?storeid=" + store_id + "&orderSn=" + _res.body.obj ;
                            } else if(_res.body.code=="41000"){
                                that.$refs.toast.show(_res.body.message + '，请返回修改订单', 3000);
                            }else if(_res.body.code=="41001"){
                                that.$refs.confirm.show({
                                    title:"确认提交",
                                    content:_res.body.message+"，是否继续支付有货商品？",
                                    confirm:function(){
                                        Vue.http.post(APIJAVA + 'c/mobile/order/submit?shopId='+ store_id+"&cartIds="+_res.body.obj.cartIds+"&addressId="+that.addrid+"&couponIds="+_couponIds+"&couponCodes="+_couponCodes, { }, {
                                            emulateJSON: false
                                        }).then(function(_result){
                                            if (_result.body.code==1) {
                                                window.location.href = "order-details.html?storeid=" + store_id + "&orderSn=" + _result.body.obj;
                                            }else{
                                                that.$refs.toast.show(_res.body.message, 3000);
                                            }
                                        })
                                    }
                                });

                            }else{
                                 that.$refs.toast.show(_res.body.message, 3000);
                            }
                        })
                    } else {
                        this.$refs.toast.show('正在提交，请稍等...');
                    }
                },
                chkfreight:function(){
                    Vue.http.get(APIJAVA+"c/mobile/order/calcFreight?shopId="+store_id+"&cartIds="+n_cartid+"&addressId="+this.addrid).then(function (_result)   {
                        this.freight=_result.body.obj
                }.bind(this))
                },
                chkstock:function(){
                    Vue.http.get(APIJAVA+"c/mobile/order/checkInv/json?shopId="+store_id+"&cartIds="+n_cartid+"&addressId="+this.addrid+"&couponIds="+_couponIds).then(function(_res){
                        if (_res.body.code==1||_res.body.code=="41001"||_res.body.code=="41000") {
                            this.stock_json=_res.body;
                        }else{
                            this.$refs.toast.show(_res.body.message , 3000);
                        }
                    }.bind(this))
                }
                
            },
            computed: {
                receviercell: function() {
                    if (this.addrdetail.mobile) {
                        var tmp_cell = String(this.addrdetail.mobile);
                        tmp_cell = tmp_cell.substring(0, 3) + "****" + tmp_cell.substring(7);
                        return tmp_cell;
                    }
                },
                addr_link: function() {
                    if (bn_cartid) {
                        return "selected-address.html?storeid=" + store_id + "&bncartid=" + n_cartid + "&addressId=" + addressId + '&couponIds=' + this.coupon_id + '&amount=' + this.coupon_amount
                    } else {
                        return "selected-address.html?storeid=" + store_id + "&cartIds=" + n_cartid + "&addressId=" + addressId + '&couponIds=' + this.coupon_id + '&amount=' + this.coupon_amount
                    }
                }
            }
        });
    </script>
</body>

</html>
